package com.pengtu.gsj.service.impl.lzgl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pengtu.gsj.dao.base.Page;
import com.pengtu.gsj.dao.base.QueryFilter;
import com.pengtu.gsj.dao.lzgl.RoadSupInNoteDao;
import com.pengtu.gsj.entity.app.Attachment;
import com.pengtu.gsj.entity.lzgl.RoadSupInNote;
import com.pengtu.gsj.service.lzgl.RoadSupInNoteService;
import com.pengtu.gsj.service.system.SystemManageService;

@Service
@Transactional
public class RoadSupInNoteServiceImpl implements RoadSupInNoteService{

	@Autowired
	private RoadSupInNoteDao roadSupInNoteDao;
	@Autowired
	private SystemManageService systemManageService;
	
	@Override
	public void saveRoadSupInNote(RoadSupInNote roadSupInNote){
		roadSupInNoteDao.save(roadSupInNote);
	}
	
	@Override
	public Page<RoadSupInNote> findRoadSupInNote(Page<RoadSupInNote> page, final QueryFilter queryFilter){
		return roadSupInNoteDao.findPage(page, queryFilter);
	}
	
	@Override
	public RoadSupInNote getRoadSupInNoteById(String id){
		return roadSupInNoteDao.get(id);
	}
	
	@Override
	public void  delateRoadSupInNote(RoadSupInNote roadSupInNote){
		if(roadSupInNote.getAttachments() != null){
			for(Attachment attachment : roadSupInNote.getAttachments()){
				systemManageService.deleteAttachment(attachment);
			}
		}
		roadSupInNoteDao.delete(roadSupInNote);
	}

	/**
	 * 适用：获得公路监督巡查获取 路政基层执法站所
	 */
	@Override
	public List<RoadSupInNote> geRoadSupInNoteSignOrg(QueryFilter queryFilter) {
		return roadSupInNoteDao.find(queryFilter, "year", true);
	}

	/**
	 * 适用：用于检查新增或修改公路监督巡查时检查 年份+基层执法所 是否已经存在
	 * @param year 输入的年份
	 * @param signOrg 输入的基层执法所
	 * @param id 该条记录的id
	 * @return true or false
	 */
	@Override
	public Boolean checkYearOrg(String year, String signOrg, String id) {
		//1、如果id不为空的话，如果是不修改（或修改前后一样）返回true，否则按新增操作处理
		if (StringUtils.isNotEmpty(id)) {
			String oldYear = roadSupInNoteDao.get(id).getYear();
			String name = roadSupInNoteDao.get(id).getSignOrg();
			if (oldYear.equals(year) && name.equals(signOrg)) {
				return true;
			} else {
				return checkSame(year, signOrg);
			}
		} else {
			//2、如果id为空时，则用判断方式判断是否存在year的同时存在signOrg
			return checkSame(year, signOrg);
		}
	}
	
	public Boolean checkSame(String year, String signOrg){
		Boolean flag = true;
		if (StringUtils.isEmpty(year) || StringUtils.isEmpty(signOrg)) {
			return true;
		} else {
			List<RoadSupInNote> supInLists = roadSupInNoteDao.findBy("year", year);
			for (RoadSupInNote roadSupInNote : supInLists) {
				if (flag == true) {
					flag = signOrg.equals(roadSupInNote.getSignOrg()) ? false : true;
				}
			}
		}
		return flag;
	}
}
